package com.udi.project.business.upload.diup.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.udi.common.utils.poi.ExcelUtil;
import com.udi.framework.aspectj.lang.annotation.Log;
import com.udi.framework.aspectj.lang.enums.BusinessType;
import com.udi.framework.web.controller.BaseController;
import com.udi.framework.web.domain.AjaxResult;
import com.udi.framework.web.page.TableDataInfo;
import com.udi.project.business.utils.excel.utils.ExcelListUtil;
import com.udi.project.business.upload.diup.domain.*;
import com.udi.project.business.upload.diup.service.GetDiupMesService;
import com.udi.project.business.upload.utils.ErrorTest;
import com.udi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/upload/di")
public class DiupController extends BaseController {

    private String prefix = "upload/diup";

    @Autowired
    ExcelListUtil excelListUtil;

    @Autowired
    GetDiupMesService getDiupMesService;

    @Autowired
    ErrorTest errorTest;

    @RequiresPermissions("upload:main:view")
    @GetMapping("/main")
    public String diupmain1(){
        return prefix + "/main";
    }

    @RequiresPermissions("upload:mainls:view")
    @GetMapping("/mainls")
    public String diupls(){
        return prefix + "/mainls";
    }



    @GetMapping("/detailView/{Id}")
    public String diupdetail(@PathVariable("Id") Integer id, ModelMap mmap){

        DeviceData deviceData = getDiupMesService.getDeviceDataById(id);
        mmap.put("Data",deviceData);
        mmap.put("Package", getDiupMesService.getDevicePackageById(deviceData.getZXXSDYCPBS()));
        mmap.put("Storage", getDiupMesService.getDeviceStorageById(deviceData.getZXXSDYCPBS()));
        mmap.put("Clinical", getDiupMesService.getDeviceClinicalById(deviceData.getZXXSDYCPBS()));
        return prefix + "/detail";
    }

    @GetMapping("/addView")
    public String diupadd(){
        return prefix + "/add";
    }

    @GetMapping("/updateView/{Id}")
    public String diupdate(@PathVariable("Id") Integer id, ModelMap mmap){
        DeviceData deviceData = getDiupMesService.getDeviceDataById(id);
        mmap.put("Data",deviceData);
        mmap.put("Package", getDiupMesService.getDevicePackageById(deviceData.getZXXSDYCPBS()));
        mmap.put("Storage", getDiupMesService.getDeviceStorageById(deviceData.getZXXSDYCPBS()));
        mmap.put("Clinical", getDiupMesService.getDeviceClinicalById(deviceData.getZXXSDYCPBS()));
        return prefix + "/edit";
    }


    /**
     * 查询列表
     * @param data
     * @return
     */
    @RequiresPermissions("upload:diup:list")
    @RequestMapping("/list")
    @ResponseBody
    public TableDataInfo list(dt_di_indentityVo data){
        startPage();
        List<dt_di_indentityVo> list = getDiupMesService.getDiupMes(data);
        return getDataTable(list);
    }

    /**
     [file]* @return com.udi.framework.web.domain.AjaxResult
     * @author yuxin
     * @creed: di关联关系批量导入
     * @date 2021/10/8 17:15
     */
    @RequiresPermissions("upload:diup:import")
    @PostMapping("/import")
    @ResponseBody
    public AjaxResult importData(MultipartFile file)
    {
        try {
           return excelListUtil.parsing(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("失败");
        }
    }


    /**
     * @param
     * @return 添加
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:23
     */
    @RequiresPermissions("upload:diup:add")
    @RequestMapping("/add")
    @ResponseBody
    public AjaxResult addData(@RequestBody BaseData dateSet)
    {
        try {
            return getDiupMesService.addData(dateSet);
        } catch (RuntimeException e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * @param
     * @return 更新
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:23
     */
    @RequiresPermissions("upload:diup:edit")
    @RequestMapping("/edit")
    @ResponseBody
    public AjaxResult editData(Integer data)
    {
        try {
            return toAjax(getDiupMesService.editData(data));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * @param
     * @return 删除
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:23
     */
    @RequestMapping("/remove")
    @ResponseBody
    public AjaxResult removeData(String ids)
    {
        try {
            return toAjax(getDiupMesService.removeData(ids));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * @param ids 永久删除操作
     * @return Ajaxresult
     * @author yuxin
     * @creed: Talk is cheap,show me the code
     * @date 2021/10/18 14:23
     */
    @RequestMapping("/del")
    @ResponseBody
    public AjaxResult delData(String ids)
    {
        try {
            return toAjax(getDiupMesService.delData(ids));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * di填报验证
     * @return AjaxResult
     *
     */
    @RequestMapping("/check")
    @ResponseBody
    public AjaxResult check(String data){

        String[] str = data.split(",");
        List<Product> pro = new ArrayList<>();
        for (int i = 0; i < str.length; i++) {
            Product product = new Product();
            product.setZXXSDYCPBS(str[i]);
            pro.add(product);
        }
        try {
            JSONObject msg = getDiupMesService.checkByIds(pro);
            if(Integer.parseInt(msg.getString("returnCode")) == 1){
                return AjaxResult.success(msg.getString("returnMsg"));
            }else {
                return errorTest.error(msg);
            }
        }catch (Exception e){
            return error("服务器出现异常！异常原因："+e.getMessage());
        }
    }

    /**
     *
     * @Description: DI申报，如果成功则自动做提交动作
     *  what 申报表单@param
     * @return: com.udi.framework.web.domain.AjaxResult
     * @Date: 2021/8/11 10:15
     * 前端需要在JSON中添加use=0的字段【重要】List<Product> what List<Product> what
     * http://localhost:8080/digener/declare
     */
    @Log(title = "DI申报", businessType = BusinessType.OTHER,isSaveRequestData=true)
    @RequestMapping("/declare")
    @ResponseBody
    public AjaxResult declare(@RequestParam("mis") String mis,@RequestParam("deviceClinical") String deviceClinical,@RequestParam("devicePackage") String devicePackage,@RequestParam("deviceStorage") String deviceStorage) {

        List<DeviceClinical> cal = JSON.parseArray(deviceClinical, DeviceClinical.class);
        List<DevicePackage> pkg = JSON.parseArray(devicePackage, DevicePackage.class);
        List<DeviceStorage>  storage = JSON.parseArray(deviceStorage, DeviceStorage.class);

        Product1 pro = JSON.parseObject(mis, Product1.class);
        pro.setDeviceClinicalList(cal);
        pro.setDevicePackageList(pkg);
        pro.setDeviceStorageList(storage);
        System.out.println("pro------------>"+pro);
        try {
            return getDiupMesService.declare(pro);
        }catch (IOException e){
            System.out.println(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 导入模板下载
     * @return
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 查询完整的di信息，下拉补全，根据名称获得规格，从而获得最小销售单元产品标识
     * @param data
     * @return JSONArray
     */
    @RequestMapping("/dropdown")
    @ResponseBody
    public JSONObject getdropdown(String data){
        JSONObject array = getDiupMesService.getDiup(data);
        return array;
    }
}
